package org.cweili.vehicle.util

import com.alibaba.fastjson.JSONObject

/**
 * JSON
 *
 * @author Cweili
 * @version 2013年7月25日 下午11:46:34
 *
 */
class JSON {

	static byte getByte(JSONObject obj, key) {
		try {
			return obj.getByteValue(key)
		} catch (Exception e) {
			return 0
		}
	}

	static int getInteger(JSONObject obj, key) {
		try {
			return obj.getIntValue(key)
		} catch (Exception e) {
			return 0
		}
	}

	static long getLong(JSONObject obj, key) {
		try {
			return obj.getLongValue(key)
		} catch (Exception e) {
			return 0
		}
	}

	static String getString(JSONObject obj, key) {
		try {
			return obj.getString(key)
		} catch (Exception e) {
			return ""
		}
	}

	static Date getDate(JSONObject obj, yearKey, MonthKey, dateKey) {
		int year = getInteger(obj, yearKey)
		int month = getInteger(obj, MonthKey) - 1
		int date = getInteger(obj, dateKey)

		if (year < 1970 || year > 2038) {
			year = Calendar.getInstance().get(Calendar.YEAR)
		}
		if (month < 0 || month > 11) {
			month = Calendar.getInstance().get(Calendar.MONTH)
		}
		def calendar = new GregorianCalendar(year, month, 1)
		if (date < 1 || date > calendar.getMaximum(Calendar.DATE)) {
			date = Calendar.getInstance().get(Calendar.DATE)
		}

		calendar.set(Calendar.DATE, date)

		return new Date(calendar.getTimeInMillis())
	}

	static JSONObject parseObject(json) {
		try {
			return JSONObject.parseObject(json)
		} catch (Exception e) {
			return null
		}
	}
}
